package com.zu.commu.remote.handle;

import com.zu.commu.exception.CommuException;
import com.zu.commu.interf.gprs.ProcessOnLine;
import com.zu.commu.remote.process.GprsProcess;
import com.zu.commu.remote.session.Session;
import com.zu.commu.remote.session.SessionManager;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class HandleGPRS {
	private static Logger log = Logger
			.getLogger("com.automic.commu.remote.handle.HandleGPRS");
	private Session se;

	public HandleGPRS(Session se) {
		this.se = se;
	}

	private String byte2Hex(byte[] b) throws CommuException {
		String rString = "";
		String temp = "";
		try {
			for (int i = 0; i < b.length; i++) {
				int c = b[i];
				temp = Integer.toHexString(c & 0xFF);
				if (temp.length() == 1) {
					temp = "0" + temp;
				}
				rString = rString + temp;
			}
		} catch (Exception e) {
			throw new CommuException().setMessage("字节数组转换成十六进制的字符串出错！", null);
		}
		return rString;
	}

	public void processData(int threadNum, byte[] bs) {
		if (bs == null) {
			log.error("得到远端的数据是null !!!");
			return;
		}

		boolean errror = false;
		String gprsId = geGPRSIDFromSession(bs);
		//如果没有上线数据gprsId
		if (gprsId == null) {
			try {
				gprsId = handleOnLine(bs);
			} catch (Exception e) {
				errror = true;
				try {
					String hex = byte2Hex(bs);
					log.error("分析上线的数据[出错]" + e.getMessage() + "(上线数据是:" + hex
							+ ")");
				} catch (Exception ex) {
				}
			}
		}
		if ((!errror) && (Level.INFO.isGreaterOrEqual(log.getEffectiveLevel()))) {
			try {
				String hex = byte2Hex(bs);
				log.info("得到远端(GPRSID=" + this.se.getAttribute("gprsId")
						+ ")的数据:" + hex);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		if (gprsId == null) {
			this.se.close();
			return;
		}

		this.se.refreshHeartBeatTime();

		new GprsProcess(this.se).analyseData(threadNum, bs);
	}

	private String geGPRSIDFromSession(byte[] bs) {
		String id = (String) this.se.getAttribute("gprsId");
		return id;
	}

	private String handleOnLine(byte[] bs) throws Exception {
		String gprsId = null;
		String gprsIp = null;
		ProcessOnLine ponline = new ProcessOnLine();
		try {
			String[] simIdIp = ponline.getGPRS_ID_IP(bs);

			gprsId = simIdIp[0];
			gprsIp = simIdIp[1];
			this.se.setAttribute("gprsId", gprsId);
			this.se.setAttribute("GPRSIp", gprsIp);
			SessionManager sm = SessionManager.instance();
			sm.mapSession(gprsId, this.se);
			return gprsId;
		} catch (Exception e) {
			throw e;
		}
	}
}